package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.mapper.user.UserOderMapper;
import com.sky.pojo.AddressBook;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import com.sky.service.user.UserOderService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class UserOderServiceImpl implements UserOderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserOderMapper userOderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LocalDateTime getEstimatedDeliveryTime(Integer shopId, String customerAddress) {
        //规则：预计送到时间为：当前时间 + 菜品制作时间 + 配送时间 + 预留时间

        //菜品制作时间
        Integer cartTime = shoppingCartMapper.getMakeTimeByUserId(BaseContext.getCurrentId());
        log.info("菜品制作时间：{}", cartTime);
        //获取商家地址
        String shopAddress = merchantMapper.getShopAddress(shopId).getShopAddress();
        //配送时间
        Map<String, String> map = MapUtils.gaodeTwoPointCostDistanceAndTimeByAddress(shopAddress, customerAddress);
        String s = map.get("duration");
        log.info("==================================={}", s);
        Integer durationTime = Integer.parseInt(map.get("duration"));
        log.info("配送时间：{}", durationTime);

        Integer time = cartTime * 60 + durationTime + 600;
        log.info("总耗时：{}", time);
        LocalDateTime dateTime = LocalDateTime.now().plusSeconds(time);
        return dateTime;
    }

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        String key = "ORDER-CREATE:" + BaseContext.getCurrentId();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "aa", Duration.ofSeconds(10));
        if (!flag){
            log.info("未获得锁");
            throw new BaseException("请勿重复下单");
        }
        log.info("获得锁");

        //搞清楚:本质就是存两张表 订单表和明细表先存订单表，然后获取订单id再存明细表
        //所有的逻辑就一个，封装表里面需要的数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setAmount(dto.getAmount());



        AddressBook addressBook = addressBookMapper.findById(dto.getAddressBookId());
        if (addressBook == null){
            throw new BaseException("地址为空");
        }
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() +addressBook.getDetail());

        //订单完成时间
        Integer cartTime = shoppingCartMapper.getMakeTimeByUserId(BaseContext.getCurrentId());
        orders.setMealTime(LocalDateTime.now().minusMinutes(cartTime));
        userOderMapper.insert(orders);

        //插入订单详细表
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryCart(BaseContext.getCurrentId());
        List<OrderDetail> orderDetailList = new ArrayList<>();
        OrderDetail detail = new OrderDetail();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BeanUtils.copyProperties(shoppingCart,detail);
            detail.setOrderId(orders.getId());
            orderDetailList.add(detail);

        }

        orderDetailMapper.insertOrderDetail(orderDetailList);
        OrderSubmitVO result = OrderSubmitVO.builder().orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .build();
        shoppingCartMapper.deleteShop(BaseContext.getCurrentId());
        return result;
    }
}
